<?php
namespace control;
// 回款计划登记
class paybackPlanClass extends adIndexClass
{
    private const page  = 'paybackPlan'; # 权限
    private const table       = 'sales_contract'; # 数据表
    private const tablePay    = 'sales_contract_payback'; # 回款表
    private const title = '回款计划';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'date'          => [
                        'name'  => '{l.paybackPlan.homeSearch.date}',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'clientName' => [
                        'name'  => '{l.paybackPlan.homeSearch.clientName}',
                        'width' => 300,
                    ],
                    'name'  => [
                        'name'  => '{l.paybackPlan.homeSearch.name}',
                        'width' => 300,
                    ],
                    'money'         => [
                        'name'  => '{l.paybackPlan.homeSearch.money}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stage'          => [
                        'name'  => '{l.paybackPlan.homeSearch.stage}',
                        'width' => 220,
                    ],
                    'text'          => [
                        'name'  => '{l.paybackPlan.homeSearch.text}',
                        'width' => 220,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('paybackPlan.homeSearch.date') => text(['name' => 'date', 'laydate' => [ 'range' => '~', 'type'=> 'date'], ]),
                    L('paybackPlan.home.clientName')   => text(array("name" => "clientName")),
                    L('paybackPlan.home.name')   => text(array("name" => "name")),
                ],
                [
                    L('paybackPlan.home.stage')  => select(["name" => "stage", 'option'=>explode('，', para('salesContractStageOption')), ]),
                    L('paybackPlan.home.text') => text(["name" => "text"]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*回款计划入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "print")) {
            $button .= '<a href="javascript:;" onclick="printPage(\''.$this->get('cla').'\')" class="spanButton">'.L('paybackPlan.homeSearch.print').'</a>';
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }



    /*回款计划列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $cWhere = search([
            'like'=>[
                'clientName'=> $this->post('clientName'),
                'name'=> $this->post('name'),
            ]
        ]);
        $where .= str_replace('{{cWhere}}', $cWhere," AND orderId IN (SELECT id FROM `".self::table."` WHERE state = '已通过' {$cWhere}) ");
        //生成查询语句
        $where   .= search([
            "="    => [
                'stage'   => $this->post('stage'),
                "coid"=>self::$coid
            ],
            "like" => [
                'text'   => $this->post('text'),
            ],
        ]);
        if ($this->post('date')) {
            $where .= self::timeComparison($this->post('date'), 'date', 'date');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::tablePay, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            $info = query(self::table, " id = '{$array['orderId']}' ");
            //列表控件
            $dominate  = array(
                "box" => ["name" => "listId", "value" => $array['id']],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "clientName":
                    case "name":
                        $row[] = $info[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $money = find(array('table'=>self::tablePay,'where'=>$where,'sum'=>'money'));
        $total    = [
            'money'      => self::lostZero($money),
        ];
        //返回
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('paybackPlan.exportData.power');
        }else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::tablePay,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $info = query(self::table, " id = '{$array['orderId']}' ");
                $kehu = query('kehu', " khid = '{$info['clientId']}' ");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '计划回款日期'=>$array['date'],
                            '客户名称'=> $kehu['contactName'],
                            '合同名称'=>$info['name'],
                            '计划回款金额'=>$array['money'],
                            '阶段'=> $array['stage'],
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('paybackPlan.exportData.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('paybackPlan.exportData.fileName') . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'计划回款日期',
                    'aliasName'=>'计划回款日期',
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'合同名称',
                    'aliasName'=>'合同名称',
                ],
                [
                    'columnName'=>'计划回款金额',
                    'aliasName'=>'计划回款金额（元）',
                ],
                [
                    'columnName'=>'阶段',
                    'aliasName'=>'阶段',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ]
        };
    }
}
